package com.briup.corejava.chap12;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * UDP协议数据包的接收方
 */
public class Test072_UdpReceiver {
    public static void main(String[] args) {
        int port = 8888;
        DatagramSocket socket = null;
        DatagramPacket packet = null;
        // 准备存放数据的字节数组
        byte[] buffer = new byte[1024];
        try {
            socket = new DatagramSocket(port);
            packet = new DatagramPacket(buffer,0,buffer.length);
            // 接收端的receive方法会阻塞，等待数据包的接收
            socket.receive(packet);
            // 将接收到的数据打印出来
            System.out.println("接收到的数据为："+new String(packet.getData(),0,packet.getLength()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
